package com.heima.article.controller.v1;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.ApArticleControllerApi;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.dtos.ArticleSimpleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.media.dtos.WmNewsStatisticsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/article")
public class ApArticleController implements ApArticleControllerApi {
    @Autowired
    private ApArticleService articleService;
    @PostMapping("save")
    @Override
    public ApArticle saveArticle(@RequestBody ApArticle apArticle) {
        articleService.save(apArticle);
        return apArticle;
    }
    @GetMapping("{id}")
    @Override
    public Map findArticle(@PathVariable Long id) {
        return articleService.findArticle(id);
    }


    @GetMapping("/ids/{authorId}")
    public List<ArticleSimpleInfoDto> findArticleIdsByAuthorId(@PathVariable Long authorId){
        return articleService.findArticleIdsByAuthorId(authorId);
    }


    @PostMapping("/getByArticeIdAndAuthorId")
    public List<ApArticle> findArticleIdsByAuthorIdAndArticleId(@RequestParam("authorId") Long authorId,@RequestParam("articleId") Long articleId) {
        return articleService.list(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getAuthorId,authorId).eq(ApArticle::getId,articleId));
    }

    // 查询文章数量
    @Override
    @PostMapping("findArticleCount")
    public Integer findArticleCount(@RequestBody WmNewsStatisticsDto dto) {
        return articleService.findArticleCount(dto);
    }

    // 当前用户发布的文章ID集合
    @Override
    @PostMapping("queryArticleIds")
    public List<Long> queryArticleIds(@RequestBody WmNewsStatisticsDto dto) {
        List<ApArticle> articleList = articleService.list(
                Wrappers.<ApArticle>lambdaQuery()
                        .eq(ApArticle::getAuthorId, dto.getWmUserId())
                        .between(ApArticle::getCreatedTime, dto.getStime(), dto.getEtime())
        );
        List<Long> resultList = articleList.stream().map(apArticle -> {
            return apArticle.getId();
        }).collect(Collectors.toList());
        return resultList;
    }

    /**
     * 根据用户ID查询文章信息
     */
    @Override
    @PostMapping("findArticleByAuthorId")
    public List<ApArticle> findArticleByAuthorId(@RequestBody WmNewsStatisticsDto dto) {
        return articleService.list(
                Wrappers.<ApArticle>lambdaQuery()
                        .eq(ApArticle::getAuthorId, dto.getWmUserId())
                        .between(ApArticle::getCreatedTime, dto.getStime(), dto.getEtime())
        );
    }

}